package com.paziy.jan.thread;

import java.sql.Time;
import java.util.Random;

public class Main {

    public static void message(String text) {
        System.out.format("%s-%s: %s%n",
                Thread.currentThread().getName(),
                new Time(System.currentTimeMillis()),
                text);
    }

    private static class P3 implements Runnable {

        private Buffer<String> buffer;

        public P3(Buffer<String> buffer) {
            this.buffer = buffer;
        }

        @Override
        public void run() {

            String s;

            while((s = buffer.pop()) != null) {
                message("read from CR1 value=" + s);
            }

            message("---finished---");
        }
    }

    private static class P5 implements Runnable {

        private Buffer<String> buffer;
        private BigBuffer bigBuffer;

        public P5(Buffer<String> buffer, BigBuffer bigBuffer) {
            this.buffer = buffer;
            this.bigBuffer = bigBuffer;
        }

        @Override
        public void run() {

            Integer i1, i2;

            Random random = new Random();

            String s;

            while((s = buffer.pop()) != null) {
                i1 = random.nextInt();
                i2 = random.nextInt();

            }

        }
    }

    private static class P6 implements Runnable {

        private Buffer<String> buffer;

        public P6(Buffer<String> buffer) {
            this.buffer = buffer;
        }

        @Override
        public void run() {
            Random random = new Random();

            if(buffer.isClosed()) buffer.open();

            for (int i = 0; i < random.nextInt(10) + 2; ++i) {
                try {
                    Thread.sleep(random.nextInt(1000));
                } catch (InterruptedException e) {
                    message("was Interrupted");
                }

                if (buffer.push(String.valueOf(i))) {
                    message("write to CR1 value=" + i);
                } else {
                    message("can't write data to CR1");
                }

            }

            buffer.close();

            message("---finished---");
        }
    }

    public static void main(String[] args) {

        Buffer<String> buff = new Buffer<String>();
        buff.open();
        BigBuffer bigBuff = new BigBuffer();

        new Thread(new P3(buff), P3.class.getSimpleName()).start();

        new Thread(new P5(buff, bigBuff), P5.class.getSimpleName()).start();
        new Thread(new P6(buff), P6.class.getSimpleName()).start();


    }
}
